using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UFrame;


    /// <summary>
    /// 场景中物体的碰撞控制
    /// </summary>
    public class SelectCtrl : UFrame.IRecovery
    {
        protected ObjectPool<SelectableBox> boxPool;
        protected Dictionary<int, SelectableBox> boxDic;
        public event Action<GameObject> onSelect;

        public SelectCtrl()
        {
            boxDic = new Dictionary<int, SelectableBox>();
            boxPool = new ObjectPool<SelectableBox>(0,1,()=>new SelectableBox());
            InputAgent.Instance.RegistMouseDown(0, OnMouseDown);
        }

        public void CreateBox(GameObject target)
        {
            if(target == null) {
                return;
            }

            var box = boxPool.Allocate();
            box.Binding(target);
            var id = target.GetInstanceID();
            boxDic[id] = box;
        }
        public void ClearBox(GameObject target)
        {
            if (target == null)
            {
                return;
            }

            var id = target.GetInstanceID();
            SelectableBox box;
            if (boxDic.TryGetValue(id,out box))
            {
                if(box!= null)
                {
                    box.UnBinding();
                }
            }

        }
        public void OnRecover()
        {
            InputAgent.Instance.RemoveMouseDown(0, OnMouseDown);

            using (var enumrator = boxDic.Values.GetEnumerator())
            {
                while (enumrator.MoveNext())
                {
                    var box = enumrator.Current;
                    box.UnBinding();
                }
            }
            boxDic.Clear();
            boxPool.Reset();
            onSelect = null;
        }


        protected void OnMouseDown()
        {
            //判断是否点中盒子
            var ray = CameraAgent.MainCamera.ScreenPointToRay(Input.mousePosition);
            RaycastHit[] hits = Physics.RaycastAll(ray, 100);

            for (int i = 0; i < hits.Length; i++)
            {
                var id = hits[i].collider.gameObject.GetInstanceID();
                SelectableBox box;
                if(boxDic.TryGetValue(id,out box))
                {
                    onSelect.Invoke(box.target);
                }
            }
        }

}
